package o2sjsc.projects.erp;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import o2sjsc.core.libs.json.JSONParser;
import o2sjsc.core.libs.soap.SoapUtils;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;

public class FragHD extends Fragment implements SearchView.OnQueryTextListener {
	private static final String METHOD_NAME = "MGetContracts";
	private static final String URL = "http://erp.o2s.vn/WebServices/ERPWebService.asmx";
	ListAdapter adapter;
	// private static final String TAG_EMPLOYEE = "EMPLOYEE_NAME"; private
	static final String TAG_CONTRACTNO = "CONTRACT_CODE";
	private static final String TAG_TITLE = "FULL_TITLE";
	private static final String TAG_CUSTOMER = "CUSTOMER_NAME";
	private static final String TAG_MOBILE = "MOBILE";
	private static final String TAG_EMAIL = "EMAIL";
	ArrayList<HashMap<String, String>> jsonlist = null;
	HashMap<String, String> hash;
	ListView lv;
	View V;
	private Bundle savedState = null;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		// this is really important in order to save the state across screen
		// configuration changes for example
		//setRetainInstance(true);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		setHasOptionsMenu(true);
		V = inflater.inflate(R.layout.frag_contract, container, false);
		// Get ListView object from xml
		lv = (ListView) V.findViewById(R.id.list);
		/*
		 * if (savedInstanceState != null && savedState == null) savedState =
		 * savedInstanceState.getBundle(App.STAV); if (savedState != null) //
		 * lv.set(savedState.getCharSequence(App.VSTUP)); savedState = null;
		 */
		hash = new HashMap<String, String>();
		hash.put("username", "chieunt");
		hash.put("contractNo", "");
		hash.put("contractTitle", "");
		hash.put("cusMobile", "");
		hash.put("cusEmail", "");
		hash.put("cusName", "");
		hash.put("startIndex", "1");
		hash.put("maxRecords", "10");

		new MyAsyncTask().execute();
		return V;
	}

	class MyAsyncTask extends
			AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
		ProgressDialog progress;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = new ProgressDialog(getActivity());
			progress.setMessage("Loading...");
			progress.show();
		}

		@Override
		protected ArrayList<HashMap<String, String>> doInBackground(
				String... params) {

			// Call webservice
			String jsonString = SoapUtils.Invoke(URL, METHOD_NAME, hash);

			try {
				JSONParser jsonParser = new JSONParser();
				JSONArray json = jsonParser.getJSONFromString(jsonString);
				jsonlist = new ArrayList<HashMap<String, String>>();
				for (int i = 0; i < json.length(); i++) {

					JSONObject c = json.getJSONObject(i);
					// String vEmployee = c.getString(TAG_EMPLOYEE);
					String vContractNo = c.getString(TAG_CONTRACTNO);
					String vTitle = c.getString(TAG_TITLE);
					String vCustomer = c.getString(TAG_CUSTOMER);
					String vMobile = c.getString(TAG_MOBILE);
					String vEmail = c.getString(TAG_EMAIL);

					HashMap<String, String> map = new HashMap<String, String>();

					// adding each child node to HashMap key => value //
					// map.put(TAG_EMPLOYEE, vEmployee);
					map.put(TAG_CONTRACTNO, vContractNo);
					map.put(TAG_TITLE, vTitle);
					map.put(TAG_CUSTOMER, vCustomer);
					map.put(TAG_MOBILE, vMobile);
					map.put(TAG_EMAIL, vEmail);
					jsonlist.add(map);
				}
			} catch (Exception e) { // TODO: handle exception
				Log.e("json", "Error");
			}
			return jsonlist;
		}

		@Override
		protected void onPostExecute(ArrayList<HashMap<String, String>> jsonlist) {
			progress.dismiss();
			adapter = null;
			adapter = new SimpleAdapter(getActivity(), jsonlist,
					R.layout.list_contract, new String[] { TAG_CONTRACTNO,
							TAG_TITLE, TAG_CUSTOMER, TAG_MOBILE, TAG_EMAIL },
					new int[] { R.id.contractNo, R.id.contractTitle,
							R.id.cusName, R.id.cusMobile, R.id.cusEmail });
			FragHD.this.getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					lv.setAdapter(adapter);
					((BaseAdapter) adapter).notifyDataSetChanged();
					lv.refreshDrawableState();
					lv.invalidateViews();
					// FragmentTransaction ft = FragMent1.this.getActivity()
					// .getFragmentManager().beginTransaction();
					// ft.commit();
				}
			});

		}
	}

	@Override
	public boolean onQueryTextChange(String arg0) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean onQueryTextSubmit(String arg0) {
		hash = new HashMap<String, String>();
		hash.put("username", "chieunt");
		hash.put("contractNo", arg0);
		hash.put("contractTitle", "");
		hash.put("cusMobile", "");
		hash.put("cusEmail", "");
		hash.put("cusName", "");
		hash.put("startIndex", "1");
		hash.put("maxRecords", "10");
		new MyAsyncTask().execute();
		return true;
		// return false;
	}

	/*
	 * @Override public void onDestroyView() { super.onDestroyView(); savedState
	 * = saveState(); vstup defined here for sure vstup = null; }
	 */

}
